import time
import requests
import csv

# 读取Cookie
cokf = open("Cookie.txt", mode="r")
Cookies = cokf.read()
cokf.close()

# 读取api
apif = open("api.txt", mode="r")
url = apif.read()
apif.close()


def get_dynamic_comment(i):
    header = {
        "Cookie": Cookies,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
        "Referer": "https://you.ctrip.com/"
    }
    pageIndex = i;
    data = {
        "arg": {
            "channelType": 2,
            "collapseType": 0,
            "commentTagId": 0,
            "pageIndex": pageIndex,
            "pageSize": 10,
            "poiId": 97645,
            "sourceType": 1,
            "sortType": 3,
            "starType": 0
        },
        "head": {
            "cid": "09031106316825885070",
            "ctok": "",
            "cver": "1.0",
            "lang": "01",
            "sid": "8888",
            "syscode": "09",
            "auth": "",
            "xsid": "",
            "extension": []
        }
    }
    resp = requests.post(url, headers=header, json=data)
    print(resp.text)
    try:
        for j in range(10):
            user_id = resp.json()["result"]["items"][j]["userInfo"]["userId"]
            create_time = resp.json()["result"]["items"][j]["publishTypeTag"].split(" ")[0]
            ip_place = resp.json()["result"]["items"][j]["ipLocatedName"]
            score = resp.json()["result"]["items"][j]["score"]
            comment = resp.json()["result"]["items"][j]["content"]
            csvwriter.writerow([user_id, create_time, ip_place, score, comment])

    except TypeError:
        time.sleep(1)
        print("TypeError")
        return

    except IndexError:
        time.sleep(1)
        print("IndexError")
        return


if __name__ == '__main__':
    # 计时
    t1 = time.time()
    # 初始化评论文件
    f = open("data.csv", mode="a", encoding="utf-8")
    csvwriter = csv.writer(f)
    # csvwriter.writerow(["用户ID", "评论时间", "IP地区", "评分", "评价"])
    for i in range(1, 300):
        get_dynamic_comment(i)
        time.sleep(1)

    t2 = time.time()
    f.close()
    print("over!")
    print(f"花费时间为:{t2 - t1:.2f}秒")
